<template>
  <a-modal
    centered
    :width="640"
    title="修改密码"
    :visible="updatePwdVisible"
    @cancel="handleHideUpdatePwd"
  >
    <!--保存按钮-->
    <template slot="footer">
      <a-button @click="handleHideUpdatePwd">取消</a-button>
      <a-divider type="vertical" />
      <a-button icon="check-circle" @click="handleSubmit">保存</a-button>
    </template>
    <a-form :form="form">
      <a-form-item
        label="旧密码"
        :labelCol="{ span: 6}"
        :wrapperCol="{ span: 16 }"
      >
        <a-input
          v-decorator="[
            'oldPwd',
            { rules: [{ required: true, message: '请输入旧密码' }] },
          ]"
        />
      </a-form-item>
      <a-form-item
        label="新密码"
        :labelCol="{ span: 6}"
        :wrapperCol="{ span: 16 }"
      >
        <a-input
          v-decorator="[
            'newPwd',
            { rules: [{ required: true, message: '请输入新密码' }] },
          ]"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import md5 from "md5";
import { updatePwd } from "@/api/sysAdmin";
import { mapActions } from "vuex";
export default {
  props: {
    updatePwdVisible: {
      type: Boolean,
      required: false,
    },
  },
  data() {
    return {
      labelCol: { xs: { span: 24 }, sm: { span: 8 } },
      wrapperCol: { xs: { span: 24 }, sm: { span: 12 } }, 
      // 按钮加载状态
      loading: false,
      form: this.$form.createForm(this),
    };
  },
  methods: {
    ...mapActions(["logout"]),
    // 保存
    handleSubmit() {
      let that = this;
      this.loading = true;
      this.form.validateFields((errors, values) => {
        if (!errors) {
          values.oldPwd = md5(values.oldPwd);
          values.newPwd = md5(values.newPwd);
          updatePwd(values)
            .then((res) => {
              if (res.success) {
                that.$notification.success({ description: res.msg });
                // 直接退出到登录
                that
                  .logout()
                  .then(() => {
                    setTimeout(() => {
                      window.location.reload();
                    }, 16);
                  })
                  .catch((err) => {
                    that.$message.error({
                      title: "错误",
                      description: err.message,
                    });
                  });
              } else {
                that.$notification.error({ description: res.msg });
              }
            })
            .cache((error) => {
              that.loading = false;
            });
        } else {
          that.loading = false;
        }
      });
    },
    // 取消、关闭
    handleHideUpdatePwd() {
      this.$emit("handleHideUpdatePwd");
    },
  },
};
</script>
